package com.san.app.service.impl;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.san.app.dao.WarningSubDao;
import com.san.app.domain.WarningDTO;
import com.san.app.domain.WarningSubDO;
import com.san.app.service.WarningSubService;
import com.san.app.vo.WarningSubDTO;
import com.san.app.vo.WarningSubVO;
import com.san.common.utils.Constant;
import com.san.common.utils.ExcelUtil;
import com.san.common.utils.StringUtils;
import com.san.oa.service.NotifyService;
import com.san.oa.vo.NotifyVO;
import com.san.oms.domain.ScoreDTO;
import com.san.oms.service.ScoreService;
/**
 * 预警订阅Service实现类
 * @author SuperSR
 * @date 2019年3月18日 下午5:57:59
 *
 *
 */
@Service
public class WarningSubServiceImpl implements WarningSubService{

	@Autowired
	private WarningSubDao warningSubDao;
	
	@Autowired
	ScoreService scoreService;
	
	@Autowired
	private NotifyService notifyService;
	
	@Override
	public List<WarningDTO> subscribeList(Map<String, Object> map) {
		return warningSubDao.subscribeList(map);
	}

	@Override
	public int subscribe(WarningSubVO warningSubVO) {
		return warningSubDao.subscribe(warningSubVO);
	}

	@Override
	public int cancelSubscribe(WarningSubVO warningSubVO) {
		WarningSubDO warningSubDO = warningSubDao.getSubId(warningSubVO);
		Integer state = warningSubDO.getState();
//		Long id = warningSubDO.getId();
		if(state == 0){
			return warningSubDao.cancelSubscribe1(warningSubVO);
		}else if(state == 1){
			return warningSubDao.cancelSubscribe(warningSubVO);
		}else{
			return -1;
		}
	}

	@Override
	public int count(Map<String, Object> map) {
		return warningSubDao.count(map);
	}

	@Override
	public void doMatch(WarningSubDTO warningDTO) throws Exception {
		MultipartFile file = warningDTO.getFile();
		if (null == file || file.isEmpty()) {
			return;
		}
		// 上传文件名称
		String oldFileName = file.getOriginalFilename();
		// 文件类型-后缀
		String fileType = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
		List<List<String>> list = null;

		list = ExcelUtil.read(file.getInputStream(), fileType, false);

		if (null == list || list.size() <= 0) {
			return;
		}
		
		List<ScoreDTO> listScore = new ArrayList<ScoreDTO>();
		ScoreDTO scoreDTO = null;
		String name = null;
		String code = null;
		for (List<String> values : list) {
			if (values.size() >= 1) {
				name = values.get(0);
			} 
			if (values.size() >= 2) {
				code = values.get(1);
			}
			
			scoreDTO = scoreService.queryScore(warningDTO.getModelId(), name, code);
			listScore.add(scoreDTO);
		}
		this.saveNotify(warningDTO.getUserId(),warningDTO.getBatchNo(),listScore);
	}
	
	/**
	 * 保存数据导入系统通知
	 * @param userId
	 * @param batchNo
	 * @param listScore
	 * @throws Exception
	 */
	public void saveNotify(long userId, String batchNo,
			List<ScoreDTO> listScore) throws Exception {
		NotifyVO notifyVO = new NotifyVO();
		notifyVO.setCreateUserId(new Long(100000));

		notifyVO.setContent("预警批次号："+batchNo);
		notifyVO.setTitle("信用预警反馈通知");
		notifyVO.setDelFlag(Constant.DEL_FLAG_NORMAL);
		notifyVO.setCreateDate(new Date());
		notifyVO.setUserIds(new Long[] { userId });
		notifyVO.setStatus(Constant.OA_NOTIFY_STATUS_PUBLISH);
		notifyVO.setType(Constant.OA_NOTIFY_TYPE_SYSTEM);
		notifyVO.setRemarks("系统通知");

		// 存在错误数据
		if (listScore.size() > 0) {
			StringBuffer path = new StringBuffer(notifyService.buildPath(Constant.NOTIFY_PATH_WARNING));
			// 新文件名
			String newFileName =  "预警结果反馈_"+batchNo+".xlsx";
			notifyVO.setFilePath(path + newFileName);

			XSSFWorkbook workbook = new XSSFWorkbook();
			XSSFSheet sheet = workbook.createSheet();

			// 创建第一行
			XSSFRow row = null;
			XSSFCell cell = null;
			row = sheet.createRow(0);
			cell = row.createCell(0);
			// 设置单元格值
			ExcelUtil.setValue(cell, "企业名称/姓名");
			// 设置单元格宽度
			ExcelUtil.setWidth(sheet, cell);
			cell = row.createCell(1);
			// 设置单元格值
			ExcelUtil.setValue(cell, "统一社会信用代码/身份证号码");
			// 设置单元格宽度
			ExcelUtil.setWidth(sheet, cell);
			cell = row.createCell(2);
			// 设置单元格值
			ExcelUtil.setValue(cell, "信用等级");
			// 设置单元格宽度
			ExcelUtil.setWidth(sheet, cell);
			cell = row.createCell(3);
			// 设置单元格值
			ExcelUtil.setValue(cell, "信用分");
			// 设置单元格宽度
			ExcelUtil.setWidth(sheet, cell);
			
			for (int i = 0; i < listScore.size(); i++) {
				ScoreDTO scoreDTO = listScore.get(i);
				row = sheet.createRow(i+1);
				if (null != scoreDTO) {
					cell = row.createCell(0);
					// 设置单元格值
					ExcelUtil.setValue(cell, StringUtils.nullFormat(scoreDTO.getName()));
					cell = row.createCell(1);
					// 设置单元格值
					ExcelUtil.setValue(cell, StringUtils.nullFormat(scoreDTO.getCode()));
					cell = row.createCell(2);
					// 设置单元格值
					ExcelUtil.setValue(cell, scoreDTO.getLevelName());
					cell = row.createCell(3);
					// 设置单元格值
					ExcelUtil.setValue(cell, scoreDTO.getScore());
				}
			}

			OutputStream os = new FileOutputStream(notifyVO.getFilePath());
			workbook.write(os);
			os.close();
			workbook.close();
		}

		notifyService.save(notifyVO);
	}
}
